// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/exec/aggregate_function_registry.h>
#include <gtest/gtest.h>
#include <pollux/exec/aggregate.h>
#include <pollux/exec/aggregate_util.h>
#include <pollux/exec/window_function.h>
#include <tests/exec/AggregateRegistryTestUtil.h>
#include <pollux/functions/registerer.h>
#include <pollux/type/type.h>

namespace kumo::pollux::exec::test {

class FunctionRegistryTest : public testing::Test {
 public:
  FunctionRegistryTest() {
    registerAggregateFunc("aggregate_func");
    registerAggregateFunc("Aggregate_Func_Alias");
  }

  void checkEqual(const TypePtr& actual, const TypePtr& expected) {
    if (expected) {
      EXPECT_EQ(*actual, *expected);
    } else {
      EXPECT_EQ(actual, nullptr);
    }
  }

  void testResolveAggregateFunction(
      const std::string& functionName,
      const std::vector<TypePtr>& argTypes,
      const TypePtr& expectedReturn,
      const TypePtr& expectedIntermediate) {
    auto result = resolveAggregateFunction(functionName, argTypes);
    checkEqual(result.first, expectedReturn);
    checkEqual(result.second, expectedIntermediate);
  }
};

TEST_F(FunctionRegistryTest, hasAggregateFunctionSignature) {
  testResolveAggregateFunction(
      "aggregate_func", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregate_func", {DOUBLE(), DOUBLE()}, DOUBLE(), ARRAY(DOUBLE()));
  testResolveAggregateFunction(
      "aggregate_func",
      {ARRAY(BOOLEAN()), ARRAY(BOOLEAN())},
      ARRAY(BOOLEAN()),
      ARRAY(ARRAY(BOOLEAN())));
  testResolveAggregateFunction("aggregate_func", {}, DATE(), DATE());
}

TEST_F(FunctionRegistryTest, hasAggregateFunctionSignatureWrongFunctionName) {
  testResolveAggregateFunction(
      "aggregate_func_nonexist", {BIGINT(), BIGINT()}, nullptr, nullptr);
  testResolveAggregateFunction("aggregate_func_nonexist", {}, nullptr, nullptr);
}

TEST_F(FunctionRegistryTest, hasAggregateFunctionSignatureWrongArgType) {
  testResolveAggregateFunction(
      "aggregate_func", {DOUBLE(), BIGINT()}, nullptr, nullptr);
  testResolveAggregateFunction("aggregate_func", {BIGINT()}, nullptr, nullptr);
  testResolveAggregateFunction(
      "aggregate_func", {BIGINT(), BIGINT(), BIGINT()}, nullptr, nullptr);
}

TEST_F(FunctionRegistryTest, functionNameInMixedCase) {
  testResolveAggregateFunction(
      "aggregatE_funC", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregatE_funC_aliaS", {DOUBLE(), DOUBLE()}, DOUBLE(), ARRAY(DOUBLE()));
}

TEST_F(FunctionRegistryTest, getAggregateFunctionSignatures) {
  auto functionSignatures = getAggregateFunctionSignatures();
  auto aggregateFuncSignatures = functionSignatures["aggregate_func"];
  std::vector<std::string> aggregateFuncSignaturesStr;
  std::transform(
      aggregateFuncSignatures.begin(),
      aggregateFuncSignatures.end(),
      std::back_inserter(aggregateFuncSignaturesStr),
      [](auto& signature) { return signature->toString(); });

  auto expectedSignatures = AggregateFunc::signatures();
  std::vector<std::string> expectedSignaturesStr;
  std::transform(
      expectedSignatures.begin(),
      expectedSignatures.end(),
      std::back_inserter(expectedSignaturesStr),
      [](auto& signature) { return signature->toString(); });

  ASSERT_EQ(aggregateFuncSignaturesStr, expectedSignaturesStr);
}

TEST_F(FunctionRegistryTest, aggregateWindowFunctionSignature) {
  auto windowFunctionSignatures = getWindowFunctionSignatures("aggregate_func");
  ASSERT_EQ(windowFunctionSignatures->size(), 3);

  std::set<std::string> functionSignatures;
  for (const auto& signature : windowFunctionSignatures.value()) {
    functionSignatures.insert(signature->toString());
  }
  ASSERT_EQ(
      functionSignatures.count("(bigint,double) -> array(bigint) -> bigint"),
      1);
  ASSERT_EQ(functionSignatures.count("() -> date -> date"), 1);
  ASSERT_EQ(functionSignatures.count("(T,T) -> array(T) -> T"), 1);
}

TEST_F(FunctionRegistryTest, duplicateRegistration) {
  EXPECT_FALSE(registerAggregateFunc("aggregate_func"));
  EXPECT_TRUE(registerAggregateFunc("aggregate_func", true));
}

TEST_F(FunctionRegistryTest, multipleNames) {
  auto signatures = AggregateFunc::signatures();
  auto factory = [&](core::AggregationNode::Step step,
                     const std::vector<TypePtr>& argTypes,
                     const TypePtr& resultType,
                     const core::QueryConfig& /*config*/) {
    if (isPartialOutput(step)) {
      if (argTypes.empty()) {
        return std::make_unique<AggregateFunc>(resultType);
      }
      return std::make_unique<AggregateFunc>(ARRAY(resultType));
    }
    return std::make_unique<AggregateFunc>(resultType);
  };

  auto registrationResult = registerAggregateFunction(
      "aggregate_func1",
      signatures,
      factory,
      /*registerCompanionFunctions*/ true,
      /*overwrite*/ false);
  exec::AggregateRegistrationResult allSuccess{true, true, true, true, true};
  EXPECT_EQ(registrationResult, allSuccess);
  testResolveAggregateFunction(
      "aggregate_func1", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregate_func1_partial",
      {BIGINT(), DOUBLE()},
      ARRAY(BIGINT()),
      ARRAY(BIGINT()));

  registrationResult = registerAggregateFunction(
      {std::string("aggregate_func2")},
      signatures,
      factory,
      /*registerCompanionFunctions*/ false,
      /*overwrite*/ false);
  exec::AggregateRegistrationResult onlyMainSuccess{
      true, false, false, false, false};
  EXPECT_EQ(registrationResult, onlyMainSuccess);
  testResolveAggregateFunction(
      "aggregate_func2", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));

  auto registrationResults = registerAggregateFunction(
      std::vector<std::string>{"aggregate_func2", "aggregate_func3"},
      signatures,
      factory,
      /*registerCompanionFunctions*/ true,
      /*overwrite*/ false);
  exec::AggregateRegistrationResult allSuccessExceptMain{
      false, true, true, true, true};
  EXPECT_EQ(registrationResults[0], allSuccessExceptMain);
  EXPECT_EQ(registrationResults[1], allSuccess);
  testResolveAggregateFunction(
      "aggregate_func2", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregate_func2_partial",
      {BIGINT(), DOUBLE()},
      ARRAY(BIGINT()),
      ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregate_func3", {BIGINT(), DOUBLE()}, BIGINT(), ARRAY(BIGINT()));
  testResolveAggregateFunction(
      "aggregate_func3_partial",
      {BIGINT(), DOUBLE()},
      ARRAY(BIGINT()),
      ARRAY(BIGINT()));
}

} // namespace kumo::pollux::exec::test
